package com.jghz.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import com.jghz.framework.utils.DownloadUtils;
import com.jghz.framework.utils.SpringHolder;

@Controller
public class DownLoadController {

	@GetMapping("/excelTemplate/download/{fileName:.+}")
	public void download(HttpServletResponse response, @PathVariable("fileName") String fileName) throws IOException {
		StringBuilder path = new StringBuilder("classpath:").append("excel/").append(fileName);

		Resource resource = SpringHolder.getApplicationContext().getResource(path.toString());

		if (resource.exists()) {
			// 考虑到可能是jar包
			StringBuilder tempPath = new StringBuilder(System.getProperty("java.io.tmpdir")).append("/download");
			// 判断这个文件存在不存在
			File source = FileUtils.getFile(tempPath.toString(), fileName);
			if (!source.exists()) {

				File directory = FileUtils.getFile(tempPath.toString(), "");
				if (!directory.exists()) {
					FileUtils.forceMkdir(directory);
				}
				FileOutputStream outStream = new FileOutputStream(source);
				IOUtils.copy(resource.getInputStream(), outStream);
				DownloadUtils.download(response, source, source.getName());
				IOUtils.closeQuietly(outStream);
			} else {
				DownloadUtils.download(response, source, source.getName());
				return;
			}

		}
	}
}
